package com.leyou.trade.service.impl;

import com.leyou.auth.utils.UserContext;
import com.leyou.trade.entity.CartItem;
import com.leyou.trade.repository.CartRepository;
import com.leyou.trade.service.CartService;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author BaiZY on 2020/9/7.
 * @version 1.0
 */
@Service
public class CartServiceImpl implements CartService {

    private final CartRepository cartRepository;
    private final MongoTemplate mongoTemplate;

    public CartServiceImpl(CartRepository cartRepository, MongoTemplate mongoTemplate) {
        this.cartRepository = cartRepository;
        this.mongoTemplate = mongoTemplate;
    }

    /**
     * 添加到购物车
     * @param cartItem
     */
    @Override
    public void saveCartItem(CartItem cartItem) {
        //1.获取用户信息
        Long userId = UserContext.getUser().getId();
        cartItem = handleUpdateItem(cartItem, userId);

        //5.保存到mongoDB中
        cartRepository.save(cartItem);
    }

    private CartItem handleUpdateItem(CartItem cartItem, Long userId) {
        String id = createId(cartItem.getSkuId());

        //2.查询购物车商品
        Optional<CartItem> optional = cartRepository.findById(id);

        //3.判断购物车中是否存在于要添加商品一致的商品
        if (optional.isPresent()){
            //3.1存在,记录新的商品数量
            Integer num = cartItem.getNum();
            //3.2获取就得数据
            cartItem = optional.get();
            //3.3 数量累加
            cartItem.setNum(num + cartItem.getNum());
        }
        //4.补充数据,id,userId,时间
        cartItem.setId(id);
        cartItem.setUserId(userId);
        cartItem.setUpdateTime(new Date());
        return cartItem;
    }

    /**
     * 查询购物车列表
     * @return
     */
    @Override
    public List<CartItem> queryCartList() {
        Long userId = UserContext.getUser().getId();
        return cartRepository.findByUserId(userId);
    }

    /**
     * 修改购物车
     */
    @Override
    public void updateNum(Long skuId, Integer num) {
        mongoTemplate.update(CartItem.class)
                // 根据id匹配
                .matching(Query.query(Criteria.where("_id").is(createId(skuId))))
                // 更新num字段
                .apply(Update.update("num",num).currentDate("updateTime"))
                .first();
    }

    /**
     * 删除购物车
     */
    @Override
    public void deleteCart(Long skuId) {
        cartRepository.deleteById(createId(skuId));
    }

    /**
     * 合并购物车
     * @param cartItemList
     */
    @Override
    public void addCartItemList(List<CartItem> cartItemList) {
        //1.用户id
        Long userId = UserContext.getUser().getId();
        // 2.转换
        List<CartItem> list = cartItemList.stream()
                .map(cartItem -> handleUpdateItem(cartItem, userId))
                .collect(Collectors.toList());

        //3.新增或者修改
        cartRepository.saveAll(list);
    }

    public String createId(Long skuId){
        return String.format("u%ds%d", UserContext.getUser().getId(),skuId);
    }
}
